/**
 * @FileName: BlankcardService.java
 * @Author
 * @Description:
 * @Date 2016年2月27日 上午10:35:41
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Blankcard;
import cn.hpclub.server.util.InterfaceUtil;

public class BlankcardService{
    private static Logger log = LoggerFactory.getLogger(BlankcardService.class);

    /**
     * @Title: findBlankcard
     * @Description:分页查询白卡数据
     * @param pageNumber
     *            页码
     * @param pageSize
     *            每页数量
     * @param orgId
     *            机构ID
     * @param sqlEx
     *            SQL扩展查询条件
     * @param columns
     *            查询列名
     * @param orderBy
     *            排序方式
     * @return Page<Blankcard> 查询结果
     */
    public static Page<Blankcard> findBlankcardByPage(int pageNumber, int pageSize, int orgId, String sqlEx,
            String columns, String orderBy){
        String sqlOrgFilter = InterfaceUtil.getChlidOrgByLevelSql(orgId, Constant.MAX_ORG_LEVEL);

        Page<Blankcard> pager = searchBlankcard(pageNumber, pageSize, sqlEx, sqlOrgFilter, columns, orderBy);
        if(!pager.getList().isEmpty()){
            String orgIds = getOrgIds(pager.getList());
            List<Record> usedCountList = getUsedBlankcardCount(sqlEx, pageNumber, pageSize, orgIds, orderBy);
            putUsedCountToPager(pager.getList(), usedCountList);
        }
        return pager;
    }

    public static List<Blankcard> findBlankcard(int pageNumber, int pageSize, int orgId, String sqlEx, String columns,
            String orderBy){
        String sqlOrgFilter = InterfaceUtil.getChlidOrgByLevelSql(orgId, Constant.MAX_ORG_LEVEL);
        String sql = String.format("SELECT %s from organization as org  WHERE org.id in %s %s %s LIMIT %d, %d ",
                                   columns, sqlOrgFilter, sqlEx, orderBy, (pageNumber - 1) * pageSize, pageSize);
        List<Blankcard> list = Blankcard.dao.find(sql);
        if(!list.isEmpty()){
            String orgIds = getOrgIds(list);
            List<Record> usedCountList = getUsedBlankcardCount(sqlEx, pageNumber, pageSize, orgIds, orderBy);
            putUsedCountToPager(list, usedCountList);
        }
        return list;
    }

    /**
     * @Title: getOrgIds
     * @Description:获取查询当前页的机构ID
     * @param list
     * @return String
     */
    private static String getOrgIds(List<Blankcard> list){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < list.size(); i++){
            sb.append(list.get(i).getInt("orgId"));
            if(i < (list.size() - 1)){
                sb.append(",");
            }
        }
        String orgIds = sb.toString();
        return orgIds;
    }

    /**
     * @Title: putUsedCountToPager
     * @Description:把已使用白卡数量写入结果Pager void
     */
    private static void putUsedCountToPager(List<Blankcard> list, List<Record> usedBlankcardCountList){
        for(int i = 0; i < list.size(); i++){
            Blankcard record = list.get(i);
            Long usedCount = getUsedCount(usedBlankcardCountList, i, record.getInt("orgId"));
            record.put("used", usedCount);
            record.put("freeCount", record.getInt("SIMCardCount") - usedCount);
        }
    }

    /**
     * @Title: getUsedCount
     * @Description:获取org对应的已用白卡数量
     * @param usedBlankcardCountList
     * @param index
     * @param orgId
     * @return Long
     */
    private static Long getUsedCount(List<Record> usedBlankcardCountList, int index, int orgId){
        Long usedCount = -1L;
        int usedOrgId = usedBlankcardCountList.get(index).getInt("orgId");
        if(orgId == usedOrgId){
            usedCount = usedBlankcardCountList.get(index).getLong("cnt");
        } else{
            for(int i = 0; i < usedBlankcardCountList.size(); i++){
                usedOrgId = usedBlankcardCountList.get(i).getInt("orgId");
                if(orgId == usedOrgId){
                    usedCount = usedBlankcardCountList.get(i).getLong("cnt");
                    break;
                }
            }
        }
        if(usedCount == -1){
            log.info("orgId=" + orgId + ",usedOrgId=" + usedOrgId + ",usedCount=" + usedCount);
        }
        return usedCount;
    }

    /**
     * @Title: searchBlankcard
     * @Description:在机构表查询白卡信息
     * @param columns
     *            查询列名
     * @param orderBy
     *            排序方式
     * @return Page<Blankcard>
     */

    private static Page<Blankcard> searchBlankcard(int pageNumber, int pageSize, String sqlEx, String orgSql,
            String columns, String orderBy){
        String select = "select " + columns;
        String sql = String.format("from organization as org  where org.id in %s %s %s", orgSql, sqlEx, orderBy);
        Page<Blankcard> pager = Blankcard.dao.paginate(pageNumber, pageSize, select, sql);
        return pager;
    }

    /**
     * @Title: getUsedBlankcardCount
     * @Description:查询已使用白卡数据
     * @param orgIds
     *            待查询店铺ID
     * @param orderBy
     *            排序方式
     * @return List<Record>
     */
    private static List<Record> getUsedBlankcardCount(String sqlEx, int pageNumber, int pageSize, String orgIds,
            String orderBy){
        String orgIdFilter = getOrgIdFilter(orgIds);
        String usedSelect = "select org.id as orgId, DisplayName, SIMCardCount, (select COUNT(org_id) from sales_promotion where orgId=org_id and moduleId=3 and return_code = '0') as cnt ";
        String sql = String.format("%s from organization as org  where %s %s GROUP BY org.id %s", usedSelect,
                                   orgIdFilter, sqlEx, orderBy);
        List<Record> recordList = Db.find(sql);
        return recordList;
    }

    /**
     * @Title: getOrgIdFilter
     * @Description:获取满足查询条件的IDs
     * @param sqlEx
     * @param orgSql
     * @param pageNumber
     * @param pageSize
     * @return String
     */
    private static String getOrgIdFilter(String orgIds){
        String orgIdFilter = "";
        if(orgIds.length() != 0){
            orgIdFilter = String.format("org.id in (%s)", orgIds);
        } else{
            orgIdFilter = "1";
        }
        return orgIdFilter;
    }
}
